package com.jl.magic.utils;

import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.CountDownLatch;

public class HtmlToImage extends Application {

    private static String inputUrl;        // 要截图的网页地址
    private static String outputFilePath; // 输出图片路径
    private static int width = 1024;      // 默认宽度
    private static int height = 768;      // 默认高度

    private static CountDownLatch latch;  // 控制主线程等待

    public static void convertHtmlToPng(String url, String outputPath) throws InterruptedException {
        convertHtmlToPng(url, outputPath, 1024, 768);
    }

    public static void convertHtmlToPng(String url, String outputPath, int width, int height) throws InterruptedException {
        inputUrl = url;
        outputFilePath = outputPath;
        HtmlToImage.width = width;
        HtmlToImage.height = height;

        latch = new CountDownLatch(1);
        // 启动 JavaFX 线程
        new Thread(() -> Application.launch(HtmlToImage.class)).start();
        // 主线程等待截图完成
        latch.await();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        WebView webView = new WebView();
        webView.setMinSize(width, height);
        webView.setMaxSize(width, height);

        StackPane root = new StackPane(webView);
        Scene scene = new Scene(root, width, height);

        primaryStage.setScene(scene);
        primaryStage.setTitle("HTML Renderer");
        primaryStage.show();

        webView.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == Worker.State.SUCCEEDED) {
                System.out.println("页面加载完成，准备截图...");
                // 延迟一小段时间确保渲染完成（可选）
                new Thread(() -> {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        //ignore
                    }
                    WritableImage snapshot = webView.snapshot(new SnapshotParameters(), null);

                    try {
                        BufferedImage bufferedImage = javafx.embed.swing.SwingFXUtils.fromFXImage(snapshot, null);
                        File outputFile = new File(outputFilePath);
                        ImageIO.write(bufferedImage, "png", outputFile);
                        System.out.println("已保存截图: " + outputFile.getAbsolutePath());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        // 释放资源并通知主线程继续
                        primaryStage.close();
                        latch.countDown();
                    }
                }).start();
            }
        });

        webView.getEngine().load(inputUrl);
    }

}
